import { useState, useEffect } from "react";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Space,
  Tag,
  Tree,
  Card,
  Typography,
  Divider,
  Popover,
  Popconfirm,
  Tabs,
} from "antd";
import {
  PlusOutlined,
  TeamOutlined,
  BranchesOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import type { DataNode } from "antd/es/tree";
import { http } from "../../utils/request";
import { message } from "../../utils/customMessage";
import "./index.scss";

const { Text } = Typography;

interface RoleData {
  id: number;
  name: string;
  description?: string;
  createTime?: string;
  updateTime?: string;
  menuIds?: number[];
  userCount?: number; // 使用该角色的用户数量
  type: string;
  status: string;
  permissionCount?: number;
}

interface MenuTreeNode extends DataNode {
  key: string | number;
  title: string | React.ReactNode;
  children?: MenuTreeNode[];
  id: number;
  originalData?: any; // 保存原始菜单数据
}

interface TableParams {
  pagination: {
    current: number;
    pageSize: number;
    total?: number;
  };
}

interface RoleRecord {
  id: number;
  name: string;
  description: string;
  menuList: MenuApiData[];
}

const RoleManager = () => {
  const [roleData, setRoleData] = useState<RoleRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });
  const [modalType, setModalType] = useState<"add" | "edit">("add");
  const [selectedRole, setSelectedRole] = useState<RoleData | null>(null);
  const [menuTreeData, setMenuTreeData] = useState<MenuTreeNode[]>([]);
  const [checkedMenuKeys, setCheckedMenuKeys] = useState<React.Key[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [originalMenuData, setOriginalMenuData] = useState<any[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取角色列表
  const fetchRoleData = async (
    currentPage: number = 1,
    pageSize: number = 100
  ) => {
    setLoading(true);
    try {
      const query = `?pageNum=${currentPage}&pageSize=${pageSize}`;
      const res = await http.get(`/api/role/page${query}`);
      if (+res.status === 200 && res.data) {
        setRoleData(res.data.records || []);
        setPagination({
          current: res.data.current,
          pageSize: res.data.size,
          total: res.data.total,
        });
      } else {
        message.error(res.message || "获取角色数据失败");
      }
    } catch (_) {
      message.error("获取角色数据失败");
    } finally {
      setLoading(false);
    }
  };

  // 获取菜单树数据
  const fetchMenuTree = async () => {
    try {
      const result = await http.get("/api/menu/tree");
      if (+result.status === 200) {
        setOriginalMenuData(result.data);
        // 修改 convertToTreeData 确保处理所有层级
        const convertToTreeData = (menuList: any[]): MenuTreeNode[] => {
          return menuList.map((menu) => {
            // 优先使用 menuList，其次使用 children
            const subMenus = menu.menuList || menu.children;

            return {
              key: menu.id,
              title: (
                <span className="menu-tree-node">
                  <BranchesOutlined
                    style={{ marginRight: 8, color: "#1890ff" }}
                  />
                  {menu.menuName || menu.title}
                </span>
              ),
              id: menu.id,
              // 递归处理子菜单
              children:
                subMenus && subMenus.length > 0
                  ? convertToTreeData(subMenus)
                  : undefined,
              originalData: menu,
            };
          });
        };

        const treeData = convertToTreeData(result.data);
        setMenuTreeData(treeData);

        // 设置默认展开所有节点，确保能看到所有子菜单
        const getAllKeys = (nodes: MenuTreeNode[]): React.Key[] => {
          let keys: React.Key[] = [];
          nodes.forEach((node) => {
            keys.push(node.key);
            if (node.children && node.children.length > 0) {
              keys = keys.concat(getAllKeys(node.children));
            }
          });
          return keys;
        };
        setExpandedKeys(getAllKeys(treeData));
      } else {
        message.error(result.message || "获取菜单树失败");
      }
    } catch (error) {
      console.error("获取菜单树失败:", error);
      message.error("获取菜单树失败");
    }
  };

  useEffect(() => {
    fetchRoleData();
  }, []);

  useEffect(() => {
    fetchMenuTree();
  }, []);

  // 表格列定义
  const columns = [
    {
      title: "角色名称",
      dataIndex: "name",
      key: "name",
      render: (text: string) => <span style={{ fontWeight: 600 }}>{text}</span>,
    },
    {
      title: "描述",
      dataIndex: "description",
      key: "description",
      ellipsis: true,
    },
    {
      title: "菜单数量",
      dataIndex: "menuList",
      key: "menuCount",
      align: "center",
      render: (list: MenuApiData[]) => (
        <Tag color="blue">{list?.length || 0}</Tag>
      ),
    },
    {
      title: "菜单列表",
      dataIndex: "menuList",
      key: "menuList",
      render: (list: MenuApiData[]) => (
        <Popover
          placement="topLeft"
          title="菜单列表"
          content={list?.map((m) => m.menuName).join("、") || "无"}
        >
          <a>查看</a>
        </Popover>
      ),
    },
    {
      title: "操作",
      key: "action",
      width: 140,
      render: (_: any, record: RoleRecord) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            onClick={() => handleEdit(record as any)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除该角色？"
            onConfirm={() => handleDelete(record as any)}
          >
            <Button type="link" size="small" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理新增
  const handleAdd = () => {
    setModalType("add");
    setSelectedRole(null);
    form.resetFields();
    setCheckedMenuKeys([]);
    setIsModalVisible(true);
  };

  // 处理编辑
  const handleEdit = (record: RoleRecord) => {
    setModalType("edit");
    setSelectedRole(record);
    form.setFieldsValue(record);

    // 从 record.menuList 提取已拥有的菜单 ID（只包含当前角色实际拥有的菜单）
    const extractMenuIds = (menuList: MenuApiData[] = []): number[] => {
      const ids: number[] = [];

      menuList.forEach((menu) => {
        ids.push(menu.id);
        // 递归处理子菜单
        if (menu.menuList && menu.menuList.length > 0) {
          ids.push(...extractMenuIds(menu.menuList));
        }
      });

      return ids;
    };

    // 只选中当前角色实际拥有的菜单ID
    const currentMenuIds = extractMenuIds(record.menuList);
    console.log("当前角色拥有的菜单ID:", currentMenuIds);
    console.log("record.menuList:", record.menuList);
    setCheckedMenuKeys(currentMenuIds);

    setIsModalVisible(true);
  };

  // 处理删除
  const handleDelete = async (record: RoleData) => {
    try {
      const result = await http.post("/api/role/del", { id: record.id });
      if (+result.status === 200) {
        message.success("删除成功");
        fetchRoleData();
      } else {
        message.error(result.message || "删除失败");
      }
    } catch (error) {
      console.error("删除失败:", error);
      message.error("删除失败");
    }
  };

  // 重构菜单选中逻辑处理函数
  const handleMenuCheck = (
    checkedKeys:
      | React.Key[]
      | { checked: React.Key[]; halfChecked: React.Key[] }
  ) => {
    let keys: React.Key[];

    // 处理不同的 checkedKeys 格式
    if (Array.isArray(checkedKeys)) {
      keys = checkedKeys;
    } else {
      keys = checkedKeys.checked;
    }

    console.log("用户选中的Keys:", keys);

    // 获取完整的菜单树结构（扁平化）
    const flatMenuMap = new Map<React.Key, any>();
    const parentChildMap = new Map<React.Key, React.Key[]>(); // 父级->子级映射
    const childParentMap = new Map<React.Key, React.Key>(); // 子级->父级映射

    const buildMaps = (menus: any[], parentId?: React.Key) => {
      menus.forEach((menu) => {
        flatMenuMap.set(menu.id, menu);

        if (parentId) {
          childParentMap.set(menu.id, parentId);

          if (!parentChildMap.has(parentId)) {
            parentChildMap.set(parentId, []);
          }
          parentChildMap.get(parentId)!.push(menu.id);
        }

        // 只有当 menuList 存在且不为空时才递归处理子菜单
        const children = menu.menuList || menu.children;
        if (children && children.length > 0) {
          buildMaps(children, menu.id);
        }
      });
    };

    buildMaps(originalMenuData);

    // 直接使用用户选中的keys，不进行自动联动
    // 这样确保只有用户明确选中的菜单才会被包含
    const finalCheckedKeys = new Set<React.Key>(keys);

    const result = Array.from(finalCheckedKeys);
    console.log("最终选中的Keys:", result);
    setCheckedMenuKeys(result);
  };

  // 重构 buildSelectedMenuTree 函数，严格按照选中状态构建树
  const buildSelectedMenuTree = (
    originalData: any[],
    checkedKeys: React.Key[]
  ): any[] => {
    const result: any[] = [];

    console.log("构建菜单树 - 原始数据:", originalData);
    console.log("构建菜单树 - 选中的Keys:", checkedKeys);

    originalData.forEach((menu) => {
      // 只有当前菜单被明确选中时才处理
      if (checkedKeys.includes(menu.id)) {
        console.log(`处理菜单: ${menu.menuName} (ID: ${menu.id})`);

        const menuItem = {
          id: menu.id,
          parentId: menu.parentId || 0,
          menuName: menu.menuName || menu.title,
          title: menu.menuName || menu.title,
          url: menu.url || menu.path,
          path: menu.url || menu.path,
          description: menu.description,
          editAble: menu.editAble,
          component: menu.component,
          menuList: null as any, // 默认设为 null
        };

        // 确保至少有一个标题字段不为空
        if (!menuItem.menuName && !menuItem.title) {
          menuItem.menuName = `菜单-${menu.id}`;
          menuItem.title = `菜单-${menu.id}`;
        }

        // 确保 path 和 url 不为空
        if (!menuItem.path || !menuItem.url) {
          const defaultPath = `/menu-${menu.id}`;
          menuItem.path = menuItem.path || defaultPath;
          menuItem.url = menuItem.url || defaultPath;
        }

        // 检查原始菜单是否有子菜单数据
        const originalChildren = menu.menuList || menu.children;
        if (originalChildren && originalChildren.length > 0) {
          console.log(`菜单 ${menu.menuName} 有子菜单，检查哪些子菜单被选中`);

          // 递归处理子菜单 - 只包含被选中的子菜单
          const selectedSubMenus = buildSelectedMenuTree(
            originalChildren,
            checkedKeys
          );

          // 只有当存在被选中的子菜单时才设置 menuList
          if (selectedSubMenus.length > 0) {
            menuItem.menuList = selectedSubMenus;
            console.log(
              `菜单 ${menu.menuName} 包含 ${selectedSubMenus.length} 个被选中的子菜单`
            );
          } else {
            console.log(
              `菜单 ${menu.menuName} 没有被选中的子菜单，menuList 保持为 null`
            );
          }
        } else {
          console.log(`菜单 ${menu.menuName} 原本就没有子菜单`);
        }

        result.push(menuItem);
      } else {
        console.log(`菜单 ${menu.menuName} (ID: ${menu.id}) 未被选中，跳过`);

        // 即使父菜单未被选中，也要检查子菜单是否有被选中的
        const originalChildren = menu.menuList || menu.children;
        if (originalChildren && originalChildren.length > 0) {
          const selectedSubMenus = buildSelectedMenuTree(
            originalChildren,
            checkedKeys
          );
          // 如果有子菜单被选中，这些子菜单会在递归中被正确处理
          result.push(...selectedSubMenus);
        }
      }
    });

    console.log("构建结果:", result);
    return result;
  };

  // 修改 handleSave 函数
  const handleSave = async (values: any) => {
    try {
      let result;
      let operatedRoleId: number;

      // 生成菜单树并验证
      const menuTree = buildSelectedMenuTree(originalMenuData, checkedMenuKeys);

      if (modalType === "add") {
        // 新增角色 - 调用 save 接口
        const saveData = {
          name: values.name,
          description: values.description,
          menuList: menuTree,
        };
        console.log("新增角色数据:", saveData);
        result = await http.post("/api/role/save", saveData);
        operatedRoleId = result.data?.id;
      } else {
        // 编辑角色 - 调用 update 接口
        const updateData = {
          id: selectedRole?.id,
          name: values.name,
          description: values.description,
          menuList: menuTree,
        };
        console.log("编辑角色数据:", updateData);
        result = await http.post("/api/role/update", updateData);
        operatedRoleId = selectedRole?.id!;
      }

      if (+result.status === 200) {
        message.success(modalType === "add" ? "添加成功" : "更新成功");

        // 检查当前登录用户的角色是否与操作的角色相同
        const currentRoleId = localStorage.getItem("roleId");

        if (
          currentRoleId &&
          operatedRoleId &&
          parseInt(currentRoleId) === operatedRoleId
        ) {
          console.log("当前用户角色被修改，重新获取用户信息");

          try {
            // 重新调用 userInfo 接口获取最新数据
            const userId = localStorage.getItem("userId");
            if (userId) {
              const userInfoResult = await http.get(
                `/api/user/userInfo?id=${userId}`
              );
              localStorage.setItem(
                "userInfo",
                JSON.stringify(userInfoResult.data)
              );
              if (+userInfoResult.status === 200 && userInfoResult.data) {
                // 更新角色ID（防止角色信息变更）
                localStorage.setItem(
                  "roleId",
                  userInfoResult.data.role.id.toString()
                );

                console.log("用户信息已更新:", userInfoResult.data);

                // 触发菜单更新事件，通知Layout组件刷新侧边菜单
                window.dispatchEvent(
                  new CustomEvent("userInfoUpdated", {
                    detail: userInfoResult.data,
                  })
                );

                message.info("您的权限已更新，左侧菜单将自动刷新");
              }
            }
          } catch (error) {
            console.error("重新获取用户信息失败:", error);
            message.warning("权限更新成功，但菜单刷新失败，请重新登录");
          }
        }

        setIsModalVisible(false);
        form.resetFields();
        setCheckedMenuKeys([]);
        fetchRoleData(pagination.current, pagination.pageSize);
      } else {
        message.error(result.message || "操作失败");
      }
    } catch (error) {
      console.error("保存失败:", error);
      message.error("操作失败");
    }
  };

  // 在 Modal 的 onCancel 中也要重置选中状态
  const handleModalCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
    setCheckedMenuKeys([]);
    setSelectedRole(null);
  };

  return (
    <div
      style={{
        padding: "24px",
        backgroundColor: "#f5f5f5",
        minHeight: "100vh",
      }}
    >
      {/* 主卡片容器 */}
      <Card
        title={
          <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
            <div
              style={{
                width: "32px",
                height: "32px",
                borderRadius: "8px",
                backgroundColor: "#1890ff",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <TeamOutlined style={{ color: "#fff", fontSize: "16px" }} />
            </div>
            <div>
              <div
                style={{
                  fontSize: "18px",
                  fontWeight: "600",
                  color: "#262626",
                }}
              >
                角色管理
              </div>
              <div
                style={{ fontSize: "12px", color: "#8c8c8c", marginTop: "2px" }}
              >
                管理系统角色权限与用户分配
              </div>
            </div>
          </div>
        }
        extra={
          <Space size="middle">
            {/* 操作按钮 */}
            <Space>
              <Button
                icon={<ReloadOutlined />}
                onClick={fetchRoleData}
                loading={loading}
                style={{ borderRadius: "6px" }}
              >
                刷新
              </Button>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
                style={{
                  borderRadius: "6px",
                  background:
                    "linear-gradient(135deg, #1890ff 0%, #40a9ff 100%)",
                  border: "none",
                  boxShadow: "0 2px 8px rgba(24, 144, 255, 0.3)",
                }}
              >
                新建角色
              </Button>
            </Space>
          </Space>
        }
        style={{
          borderRadius: "12px",
          boxShadow: "0 4px 12px rgba(0, 0, 0, 0.05)",
          border: "1px solid #f0f0f0",
        }}
        bodyStyle={{ padding: "24px" }}
      >
        {/* 角色表格 */}
        <Table
          rowKey="id"
          columns={columns}
          dataSource={roleData}
          loading={loading}
          bordered
          style={{ background: "#fff", borderRadius: 8 }}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            pageSizeOptions: ["5", "10", "20", "50"],
            showQuickJumper: true,
            showTotal: (t) => `共 ${t} 条`,
            onChange: (page, size) => fetchRoleData(page, size),
          }}
        />

        {/* 角色详情/编辑Modal */}
        <Modal
          title={modalType === "add" ? "新建角色" : "编辑角色 / 权限配置"}
          open={isModalVisible}
          onOk={() => form.submit()}
          onCancel={handleModalCancel}
          width={700}
          confirmLoading={loading}
        >
          <Tabs defaultActiveKey="info">
            <Tabs.TabPane tab="基本信息" key="info">
              <Form form={form} layout="vertical" onFinish={handleSave}>
                <Form.Item
                  label="角色名称"
                  name="name"
                  rules={[{ required: true, message: "请输入角色名称" }]}
                >
                  <Input placeholder="角色名称" />
                </Form.Item>
                <Form.Item label="描述" name="description">
                  <Input.TextArea
                    rows={3}
                    maxLength={120}
                    placeholder="角色描述"
                  />
                </Form.Item>
              </Form>
            </Tabs.TabPane>
            <Tabs.TabPane tab="菜单权限" key="menu">
              <div style={{ marginBottom: 8, color: "#666", fontSize: 12 }}>
                {modalType === "edit"
                  ? `当前已选中 ${checkedMenuKeys.length} 个菜单`
                  : "请选择该角色可访问的菜单"}
              </div>
              <div style={{ marginBottom: 8, color: "#999", fontSize: 11 }}>
                说明：请明确选择每个需要的菜单项，父级菜单和子级菜单需要分别选择
              </div>
              <Tree
                checkable
                checkStrictly={true} // 开启严格模式，禁止自动联动
                treeData={menuTreeData}
                checkedKeys={checkedMenuKeys}
                expandedKeys={expandedKeys}
                onExpand={setExpandedKeys}
                onCheck={handleMenuCheck}
                style={{
                  maxHeight: 400,
                  overflow: "auto",
                  padding: "8px 12px",
                  border: "1px solid #f0f0f0",
                  borderRadius: "4px",
                }}
              />
            </Tabs.TabPane>
          </Tabs>
        </Modal>
      </Card>

      {/* 操作提示 */}
      <div
        style={{
          marginTop: "24px",
          padding: "16px",
          backgroundColor: "#f0f8ff",
          border: "1px solid #e6f4ff",
          borderRadius: "6px",
          fontSize: "12px",
          color: "#1890ff",
        }}
      >
        <div style={{ marginBottom: "4px" }}>
          <strong>💡 操作提示：</strong>
        </div>
        <div>• 点击角色卡片可查看详细信息</div>
        <div>• 使用右上角的更多按钮访问完整操作菜单</div>
        <div>• 删除角色前请确保没有关联的用户</div>
        <div>• 系统管理员角色不可删除</div>
      </div>
    </div>
  );
};

export default RoleManager;
